<template>
    <custom-page-box>
        <div class="container">
            <div class="header">
                <a-form-model ref="formInline" layout="inline" :model="formInline">
                    <a-form-model-item label="优品标题">
                        <a-input v-model="formInline.title" placeholder="优品标题" allowClear> </a-input>
                    </a-form-model-item>
                    <a-form-model-item label="分类" class="classfiy">
                        <a-cascader
                            :field-names="{ label: 'name', value: 'id', children: 'children' }"
                            :options="optionsList"
                            placeholder="请选择分类"
                            v-model="formInline.kindId"
                        />
                    </a-form-model-item>
                    <a-form-model-item label="发布状态">
                        <a-select v-model="formInline.status" placeholder="发布状态" :allowClear="true">
                            <a-select-option :value="0"> 未发布 </a-select-option>
                            <a-select-option :value="1"> 已发布 </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="省市区镇">
                        <city-cascader
                            placeholder="请选择省市区镇"
                            v-model="formInline.cityCode"
                            :key="keysCode"
                        ></city-cascader>
                    </a-form-model-item>
                    <a-form-model-item label="添加时间" class="time">
                        <a-range-picker
                            v-model="formInline.time"
                            format="YYYY-MM-DD HH:mm:ss"
                            valueFormat="YYYY-MM-DD HH:mm:ss"
                            :show-time="{
                                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')]
                            }"
                        />
                    </a-form-model-item>
                </a-form-model>
                <div class="btn">
                    <a-button @click="handleSearch">搜索</a-button>
                    <a-button @click="resetSearch">重置</a-button>
                    <a-button
                        type="primary"
                        @click="
                            () => {
                                $router.push('/fine-product/add')
                            }
                        "
                    >
                        添加
                    </a-button>
                </div>
            </div>
            <div class="tabel-group">
                <a-table
                    :columns="columns"
                    :data-source="tabeData"
                    :row-selection="rowSelection"
                    rowKey="id"
                    :pagination="false"
                    :scroll="{ y: height }"
                >
                    <span slot="index" slot-scope="text, record, index">
                        {{ (currentPage - 1) * pageSize + index + 1 }}
                    </span>
                    <template slot="sort" slot-scope="text, record">
                        <a-input
                            :value="text"
                            placeholder="输入序号进行排序"
                            @blur="handleBlur($event, record)"
                            @keyup.enter="handleBlur($event, record)"
                        />
                    </template>
                    <template slot="name" slot-scope="text, record">
                        <a-button
                            type="link"
                            @click="
                                () => {
                                    $router.push({
                                        name: 'fine-product-add',
                                        query: {
                                            id: record.id,
                                            edit: 'false'
                                        }
                                    })
                                }
                            "
                        >
                            {{ text }}
                        </a-button>
                    </template>
                    <template slot="imgUrl" slot-scope="record">
                        <img
                            style="cursor: pointer"
                            v-if="record"
                            :src="$staticUrl + record.split(',')[0]"
                            alt=""
                            @click="imgShow(record.split(','))"
                        />
                    </template>
                    <template slot="address" slot-scope="record">
                        <span
                            :title="title(record)"
                        >{{ record.province || '' }}{{ record.city || '' }}{{ record.area || ''
                        }}{{ record.town || '' }}</span>
                    </template>
                    <template slot="kind" slot-scope="record">
                        <span v-if="record"> {{ record }}</span>
                    </template>
                    <template slot="status" slot-scope="status">
                        <span> {{ status === 1 ? '已发布' : '未发布' }}</span>
                    </template>
                    <template slot="action" slot-scope="record">
                        <a-button
                            type="primary"
                            v-if="record.status === 0"
                            @click="
                                () => {
                                    $router.push({
                                        name: 'fine-product-add',
                                        query: {
                                            id: record.id
                                        }
                                    })
                                }
                            "
                        >
                            编辑
                        </a-button>
                        <a-button
                            type="danger"
                            v-if="record.status === 0"
                            @click="deleteItem(record)"
                            style="margin-left: 10px"
                        >
                            删除
                        </a-button>
                        <a-button type="danger" v-if="record.status === 1" @click="offlineItem(record)">下线</a-button>
                    </template>
                </a-table>
            </div>
            <div class="footer">
                <div class="left">
                    <span
                        class="num"
                    >已选<font>{{ selectedRowsIdList.length }}</font>条</span>
                    <a-button :disabled="offline" @click="offlineData"> 批量下线 </a-button>
                    <a-button :disabled="deleteState" @click="deleteData"> 批量删除 </a-button>
                </div>
                <a-pagination
                    v-model="currentPage"
                    show-size-changer
                    :page-size.sync="pageSize"
                    :show-total="(total) => `共 ${total} 条`"
                    :total="total"
                    show-quick-jumper
                    @change="handlePageChange"
                    @showSizeChange="handleSizeChange"
                />
            </div>
        </div>
    </custom-page-box>
</template>

<script>
import moment from 'moment'
import cityCascader from '@/components/city-cascader'
export default {
    components: {
        cityCascader
    },
    data () {
        return {
            moment,
            options: [],
            optionsList: [],
            offline: true,
            deleteState: true,
            formInline: {
                title: '',
                status: undefined,
                time: [],
                kindId: [],
                cityCode: ''
            },
            currentPage: 1,
            pageSize: 10,
            total: 0,
            tabeData: [],
            columns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    width: 80,
                    scopedSlots: { customRender: 'index' }
                },
                {
                    title: '排序',
                    dataIndex: 'sort',
                    key: 'sort',
                    scopedSlots: { customRender: 'sort' }
                },
                {
                    title: '优品标题',
                    dataIndex: 'title',
                    key: 'title',
                    ellipsis: true,
                    scopedSlots: { customRender: 'name' }
                },
                {
                    title: '图片',
                    dataIndex: 'imgUrl',
                    key: 'imgUrl',
                    scopedSlots: { customRender: 'imgUrl' }
                },
                {
                    title: '分类',
                    dataIndex: 'kind',
                    key: 'kind',
                    ellipsis: true,
                    scopedSlots: { customRender: 'kind' }
                },
                {
                    title: '省市区镇',
                    dataIndex: '',
                    key: 'address',
                    ellipsis: true,
                    scopedSlots: { customRender: 'address' }
                },
                {
                    title: '发布状态',
                    dataIndex: 'status',
                    key: 'status',
                    ellipsis: true,
                    scopedSlots: { customRender: 'status' }
                },
                {
                    title: '编辑人',
                    dataIndex: 'collector',
                    key: 'collector',
                    ellipsis: true
                },
                {
                    title: '添加时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    ellipsis: true,
                    scopedSlots: { customRender: 'createTime' }
                },
                {
                    title: '操作',
                    dataIndex: '',
                    key: 'x',
                    width: 180,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            selectedRowsIdList: [],
            height: 800,
            keysCode: 0
        }
    },
    computed: {
        rowSelection () {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    const list = selectedRows.map(item => item.status)
                    if (list.includes(0) && list.includes(1)) {
                        this.offline = true
                        this.deleteState = true
                    }
                    if (list.includes(0) && !list.includes(1)) {
                        this.deleteState = false
                    }
                    if (list.includes(1) && !list.includes(0)) {
                        this.offline = false
                    }
                    if (!list.includes(1) && !list.includes(0)) {
                        this.offline = true
                        this.deleteState = true
                    }
                    this.selectedRowsIdList = selectedRows.map(item => item.id)
                },
                getCheckboxProps: record => ({
                    props: {
                        // Column configuration not to be checked
                        id: record.id
                    }
                }),
                selectedRowKeys: this.selectedRowsIdList
            }
        }
    },
    mounted () {
        this.getTypeTree()
        this.getTableData({ currentPage: 1, pageSize: 10 })
        const dom = document.querySelector('.ant-table-wrapper')
        console.log(dom.offsetHeight)
        this.height = dom.offsetHeight - 41
    },
    methods: {
        title (item) {
            const province = item.province || ''
            const city = item.city || ''
            const area = item.area || ''
            const town = item.town || ''
            return province + city + area + town
        },
        // 获取优品分类
        async getTypeTree () {
            const res = await this.$ApiServer['fineproduct/type']()
            if (res.code === 200) {
                res.data = res.data.filter(item => item.status !== 0 && item.children && item.children.length)
                res.data.forEach((item) => {
                    item.children = item.children.filter(subItem => subItem.status !== 0)
                })
                this.optionsList = res.data
            }
        },
        handleSearch () {
            const { title, status, time, kindId, cityCode } = this.formInline
            this.getTableData({
                title,
                status,
                startTime: time.length ? String(time[0]) : null,
                endTime: time.length ? String(time[1]) : null,
                kindId: kindId[1] || null,
                cityCode,
                currentPage: 1,
                pageSize: 10
            })
        },
        resetSearch () {
            this.formInline = {
                title: '',
                status: undefined,
                time: [],
                kindId: [],
                cityCode: ''
            }
            this.keysCode++
            this.getTableData({ currentPage: 1, pageSize: 10 })
        },
        handlePageChange (page, pageSize) {
            const { title, status, time, kindId, cityCode } = this.formInline
            this.currentPage = page
            this.pageSize = pageSize
            this.getTableData({
                currentPage: page,
                pageSize,
                title,
                status,
                startTime: time.length ? String(time[0]) : null,
                endTime: time.length ? String(time[1]) : null,
                kindId: kindId[1] || null,
                cityCode
            })
        },
        handleSizeChange (current, size) {
            const { title, status, time, kindId, cityCode } = this.formInline
            this.currentPage = current
            this.pageSize = size
            this.getTableData({
                currentPage: current,
                pageSize: size,
                title,
                status,
                startTime: time.length ? String(time[0]) : null,
                endTime: time.length ? String(time[1]) : null,
                kindId: kindId[1] || null,
                cityCode
            })
        },
        // 获取列表
        async getTableData (data) {
            const res = await this.$ApiServer['fineproduct/list']({
                ...data
            })
            if (res.code === 200 || res.data) {
                this.tabeData = res.data.records || []
                this.total = Number(res.data.total)
                this.tabeData.forEach((item) => {
                    if (!item.sort) {
                        item.sort = '0'
                    }
                })
            } else {
                this.$message.error(res.message)
            }
        },
        onChange (date, dateString) {
            this.formInline.time = dateString
        },
        imgShow (urls) {
            this.$picturesModal({ urls })
        },
        async handleBlur (e, item) {
            const reg = /^([0]|[1-9][0-9]*)$/
            if (!reg.test(e.target.value)) {
                return this.$message.error('请输入正整数')
            }
            const res = await this.$ApiServer['fineproduct/sort']({
                sort: e.target.value,
                id: item.id
            })
            if (res.code === 200) {
                this.getTableData({ currentPage: 1, pageSize: 10 })
            } else {
                e.target.value = item.sort
                this.$message.error(res.message)
            }
        },
        deleteData () {
            const that = this
            this.$confirm({
                title: '提示',
                content: '您确定要删除选中的内容吗？',
                async onOk () {
                    const ids = []
                    that.tabeData.forEach((item) => {
                        if (item.status === 0) {
                            that.selectedRowsIdList.forEach((subItem) => {
                                if (subItem === item.id) {
                                    ids.push(item.id)
                                }
                            })
                        }
                    })
                    const res = await that.$ApiServer['fineproduct/delete'](ids)
                    if (res.code === 200) {
                        that.$message.success('操作成功')
                        that.currentPage = 1
                        that.pageSize = 10
                        that.getTableData({ currentPage: 1, pageSize: 10 })
                        that.selectedRowsIdList = []
                    } else {
                        that.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        deleteItem (item) {
            const that = this
            this.$confirm({
                title: '提示',
                content: '您确定要删除选中的内容吗？',
                async onOk () {
                    const res = await that.$ApiServer['fineproduct/delete']([item.id])
                    if (res.code === 200) {
                        that.$message.success('操作成功')
                        that.currentPage = 1
                        that.pageSize = 10
                        that.getTableData({ currentPage: 1, pageSize: 10 })
                        that.selectedRowsIdList = []
                    } else {
                        that.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        offlineData () {
            const that = this
            this.$confirm({
                title: '提示',
                content: '您确定要下线选中的内容吗？',
                async onOk () {
                    const ids = []
                    that.tabeData.forEach((item) => {
                        if (item.status === 1) {
                            that.selectedRowsIdList.forEach((subItem) => {
                                if (subItem === item.id) {
                                    ids.push(item.id)
                                }
                            })
                        }
                    })
                    const res = await that.$ApiServer['fineproduct/offline'](ids)
                    if (res.code === 200) {
                        that.$message.success('操作成功')
                        that.currentPage = 1
                        that.pageSize = 10
                        that.getTableData({ currentPage: 1, pageSize: 10 })
                        that.selectedRowsIdList = []
                    } else {
                        that.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        offlineItem (item) {
            const that = this
            this.$confirm({
                title: '提示',
                content: '您确定要下线选中的内容吗？',
                async onOk () {
                    const res = await that.$ApiServer['fineproduct/offline']([item.id])
                    if (res.code === 200) {
                        that.$message.success('操作成功')
                        that.currentPage = 1
                        that.pageSize = 10
                        that.getTableData({ currentPage: 1, pageSize: 10 })
                        that.selectedRowsIdList = []
                    } else {
                        that.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        }
    }
}
</script>

<style lang="less" scoped>
.container {
    border-radius: 6px;
    height: 100%;
    .header {
        width: 100%;
        padding: 10px 0;
        background-color: #ffffff;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .ant-form-inline {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            width: 100%;
            padding: 0 20px;
            ::v-deep {
                .ant-btn {
                    margin-left: 20px;
                }
                .ant-select,
                .ant-btn {
                    height: 32px;
                    line-height: 32px;
                    border-radius: 2px;
                    .ant-select-selection {
                        border-radius: 2px;
                        width: 290px;
                    }
                }
                .ant-form-item {
                    width: 28%;
                    height: 32px;
                    display: flex;
                    margin-bottom: 12px;
                    .ant-form-item-control {
                        line-height: 32px;
                        input {
                            height: 32px;
                            padding: 0;
                            padding-left: 10px;
                            width: 290px;
                        }
                    }
                    &.classfiy {
                        width: 40%;
                        .ant-form-item-label {
                            margin-right: 28px;
                        }
                        input {
                            width: 400px;
                        }
                    }
                    &.time {
                        width: 40%;
                        .ant-form-item-control-wrapper {
                            .ant-calendar-picker-input {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                padding: 4px 0;
                            }
                        }
                        .ant-calendar-picker {
                            width: 400px !important;
                        }
                    }
                }
            }
        }
        .btn {
            margin-top: 10px;
            padding: 0 20px;
            border-top: 1px solid rgb(224, 221, 221);
            padding-top: 10px;
            button + button {
                margin-left: 20px;
            }
        }
    }
    .tabel-group {
        background-color: #fff;
        height: calc(100vh - 165px - 50px - 90px);
        .ant-table-wrapper {
            height: calc(100vh - 165px - 50px - 90px);
        }
        ::v-deep {
            .ant-btn-danger {
                background-color: #fd5454;
            }
            .ant-btn-link {
                display: block;
                width: 100%;
                text-align: left;
                span {
                    display: block;
                    width: 100%;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    color: @primary-color !important;
                    text-decoration: underline;
                }
            }
        }
    }
    .footer {
        height: 50px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        margin-top: 10px;
        background: #ffffff;
        border-radius: 6px;
        .left {
            display: flex;
            align-items: center;
            .num {
                font-size: 20px;
                color: #999999;
                margin-right: 40px;
                position: relative;
                &::after {
                    content: '';
                    position: absolute;
                    right: -20px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 1px;
                    height: 40px;
                    background-color: #f3f3f3;
                }
                font {
                    font-size: 32px;
                }
            }
            button {
                background: #ffffff;
                border: 1px solid #666666;
                color: #666666;
            }
            button + button {
                margin-left: 10px;
            }
        }
        ::v-deep {
            .ant-pagination {
                .ant-pagination-disabled {
                    a {
                        background: #f2f2f2;
                    }
                }
                .ant-pagination-item-active {
                    background: @primary-color;
                    border: none;
                    a {
                        color: #ffffff;
                    }
                }
            }
        }
    }
}
</style>
